package yxy.apple.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.ByteBuffer;

public class FileUtility {
	/**
	 * 自动创建文件的各级父路径 如果文件存在则跳过处理
	 * 
	 * @param file
	 * @throws IOException
	 */
	public static void create(File file) throws IOException {
		try {
			if (!file.exists() || !file.isFile()) {
				File parent = file.getParentFile();
				if (parent != null) {
					FileUtility.make(parent);
				}
				file.createNewFile();
			}
		} catch (Exception e) {
			throw new IOException(e);
		}
	}

	/**
	 * 自动按需创建各级路径
	 * 
	 * @param dir
	 * @throws IOException
	 */
	public static void make(File dir) throws IOException {
		if (!dir.exists() || !dir.isDirectory()) {
			File parent = dir.getParentFile();
			if (parent != null) {
				FileUtility.make(parent);
			}
			dir.mkdir();
		}

	}

	/**
	 * 删除当前目录及所有其下文件，慎用！
	 * 
	 * @param dir
	 * @throws IOException
	 */
	public static void remove(File dir) throws IOException {
		if (dir.exists()) {
			if (dir.isDirectory()) {
				File[] children = dir.listFiles();
				for (File child : children) {
					remove(child);
				}
			}
			dir.delete();
		}
	}

	public static int copy(File source, File destination) throws IOException {
		int length = 0;
		FileUtility.create(destination);
		FileInputStream in = new FileInputStream(source);
		FileOutputStream out = new FileOutputStream(destination);
		byte[] buffer = new byte[8192];
		while (true) {
			int got = in.read(buffer);
			if (got < 0) {
				break;
			} else {
				out.write(buffer, 0, got);
				length += got;
			}
		}
		out.flush();
		out.close();
		in.close();
		return length;
	}

	public static byte[] read(File file) throws IOException {
		return read(file, (int) file.length());
	}

	public static byte[] read(File file, int length) throws IOException {
		ByteBuffer buffer = ByteBuffer.allocate(length);
		FileInputStream is = new FileInputStream(file);
		try {
			byte[] bytes = new byte[8192];
			int got = is.read(bytes);
			int saved = 0;
			while (got != -1) {
				buffer.put(bytes, 0, got);
				saved += got;
				if (saved >= length) {
					break;
				} else {
					got = is.read(bytes);
				}
			}
		} catch (Exception e) {
			throw new IOException(e);
		} finally {
			is.close();
		}
		return buffer.array();
	}

	/** 获取文件夹下的所有文件 */
	public static File[] getFiles(String dir) {
		return getFiles(dir, null);
	}

	/** 获取文件夹下特定扩展名的所有文件 */
	public static File[] getFiles(String dir, String extension) {
		File[] files = new File(dir).listFiles(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				if (extension == null) {
					return true;
				}
				return name.endsWith(extension);
			}
		});
		return files;
	}

	/** 获取不带扩展名的文件名 */
	public static String getFileNameWithoutExtension(File file) {
		String filename = file.getName().replaceFirst("[.][^.]+$", "");
		return filename;
	}
}
